# !/usr/bin/env/python3
# -*- coding: utf-8 -*-
# @Author  : 影子
# @Time    : 2023/11/26 22:23
# @File    : screen.py
# @Software: PyCharm
"""没有做主题皮肤"""
import datetime
import os
import random
import re
import socket
import string
import subprocess
import threading
import time as ti
import tkinter as tk
from threading import Thread
from time import sleep
from time import time
from tkinter import filedialog
from tkinter import messagebox
from tkinter import ttk
import json
import difflib
from tkinter.constants import BOTH, YES

import segno

from main.paths import paths
from main.logs import logger

cmd_device = "16010326"
cmd_adb = f"adb.exe -s {cmd_device}"

logger.info("******************************starting******************************\n")


def initialize():
    """初始化运行"""
    global cmd_adb, cmd_device
    dev_list = []
    device = subprocess.check_output("adb.exe devices", shell=True, stderr=subprocess.STDOUT, text=True)
    try:
        regex = r"(\S+)"
        matches = re.findall(regex, device)
        output_list = [(matches[4:][i], matches[4:][i + 1]) for i in range(0, len(matches[4:]), 2)]
        for i in range(len(output_list)):
            if output_list[i][1] == "device":
                dev_list.append(output_list[i][0])
        cmd_device = dev_list[0]
        cmd_adb = f"adb.exe -s {cmd_device}"
        return dev_list
    except Exception as e:
        logger.error(e)
        return e


def time_stamp():
    """时间戳函数"""
    return int(time())


def execute_command(cmd):
    """命令执行函数"""
    try:
        result = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT, text=True, encoding="utf-8",
                                         creationflags=subprocess.CREATE_NO_WINDOW)
        return result
    except subprocess.CalledProcessError as e:
        return f"命令执行出错：{e.output}"


def show_basic():
    """基本功能"""
    reset_frame()

    def device_lists():
        """获取设备列表"""
        try:
            csz = initialize()
            string = '\n'.join(csz)
            logger.info(string)
            if string == "":
                device_lists_text_box.delete(1.0, tk.END)
                device_lists_text_box.insert(tk.END, "暂未查到设备，请检查设备连接状态。")
            else:
                device_lists_text_box.delete(1.0, tk.END)
                device_lists_text_box.insert(tk.END, string)
        except TypeError as error:
            logger.error(error)
            device_lists_text_box.delete(1.0, tk.END)
            device_lists_text_box.insert(tk.END, f"暂未查到设备，请检查设备连接状态。\n{error}")

    device_lists_button = tk.Button(main_frame, text="查询连接设备SN号", command=device_lists)
    device_lists_button.place(x=55, y=10)
    device_lists_text_box = tk.Text(main_frame, width=30, height=8)
    device_lists_text_box.place(x=10, y=50)

    def appoint_device():
        """指定连接设备"""
        global cmd_device, cmd_adb
        appoint_device_input = appoint_device_name_entry.get(1.0, tk.END).strip()
        if not appoint_device_input:
            appoint_device_input = cmd_device
            cmd_adb = f"adb.exe -s {appoint_device_input}"
            logger.info(f"连接设备：{cmd_adb}")
            appoint_device_name_entry.delete(1.0, tk.END)
            appoint_device_name_entry.insert(tk.END, "默认连接第一个设备")
        elif appoint_device_input:
            cmd_device = appoint_device_input
            cmd_adb = f"adb.exe -s {cmd_device}"
            logger.info(f"连接设备：{cmd_adb}")
            messagebox.showinfo("连接设备", f"设备{cmd_device}连接成功")

    appoint_device_name = tk.Label(main_frame, text="请输入设备SN号:")
    appoint_device_name.place(x=270, y=15)
    appoint_device_name.config(background="#87CEEB")
    appoint_device_name_entry = tk.Text(main_frame, width=30, height=2)
    appoint_device_name_entry.place(x=375, y=10)
    appoint_device_button = tk.Button(main_frame, text="连接设备", command=appoint_device)
    appoint_device_button.place(x=600, y=10)

    def install_apk():
        """安装apk"""
        apk_file_path = text_apk_file_path.get("1.0", tk.END).strip()
        logger.info(f"待安装设备路径：{apk_file_path}")
        if not os.path.exists(apk_file_path):
            messagebox.showerror('错误', 'APK文件不存在，请检查文件路径。')
            logger.error("APK文件不存在，请检查文件路径。")
            return
        try:
            messagebox.showinfo("安装APK", "程序安装中，请稍后……")
            execute_command(f'{cmd_adb} install {apk_file_path}')
            logger.info("APK文件已成功安装。")
            messagebox.showinfo('成功', 'APK文件已成功安装。')
        except Exception as e:
            logger.error(f'安装失败，原因：{e}')
            messagebox.showerror('错误', f'安装失败，原因：{e}')

    def choose_apk_file():
        apk_file_path = filedialog.askopenfilename(filetypes=[("APK files", "*.apk")])
        logger.info(f"选中apk：{apk_file_path}")
        if apk_file_path:
            text_apk_file_path.delete(1.0, tk.END)
            text_apk_file_path.insert(tk.END, apk_file_path)

    choose_apk_file_button = tk.Button(main_frame, text='选择APK文件', command=choose_apk_file)
    choose_apk_file_button.place(x=495, y=125)
    text_apk_file_path = tk.Text(main_frame, width=30, height=2)
    text_apk_file_path.place(x=270, y=125)
    install_button = tk.Button(main_frame, text='安装应用',
                               command=lambda: threading.Thread(target=install_apk).start())
    install_button.place(x=600, y=125)

    def uninstall_apk():
        """卸载apk"""
        package_name = entry.get(1.0, tk.END).strip()
        logger.info(f"卸载包名：{package_name}")

        def uninstall_cmd(cmd):
            """卸载命令"""
            process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
            output, error = process.communicate()
            logger.info(f"卸载结果：{output.decode('utf-8')}, {error.decode('utf-8')}")
            return output.decode('utf-8'), error.decode('utf-8')

        if package_name:
            output, error = uninstall_cmd(f"{cmd_adb} uninstall {package_name}")
            if error:
                logger.error(error)
                messagebox.showinfo("APK卸载", error)
            else:
                logger.info(output)
                messagebox.showinfo("APK卸载", output)
        else:
            logger.warning("错误：请输入程序包名称")
            messagebox.showinfo("APK卸载", "错误：请输入程序包名称")

    label = tk.Label(main_frame, text="请输入程序包名：")
    label.place(x=270, y=90)
    label.config(background="#87CEEB")
    entry = tk.Text(main_frame, width=30, height=2)
    entry.place(x=375, y=85)
    uninstall_button = tk.Button(main_frame, text="卸载应用",
                                 command=lambda: threading.Thread(target=uninstall_apk).start())
    uninstall_button.place(x=600, y=85)

    def open_tcpip():
        """开启无线连接"""
        wifi_wlan = execute_command(f"{cmd_adb} shell ifconfig wlan0")
        ip_pattern = r'inet addr:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
        ip_match = re.search(ip_pattern, wifi_wlan)
        try:
            tcpip_address = ip_match.group(1)
            logger.info(f"ip地址是：{tcpip_address}")
            execute_command(f"{cmd_adb} tcpip 5555")
            sleep(0.1)
            os.popen(f"{cmd_adb} connect {tcpip_address}:5555")
            logger.info("无线连接开启成功")
            messagebox.showinfo("无线连接", "无线连接开启成功")
        except AttributeError as e:
            logger.error(f"无线开启失败：{e}")
            messagebox.showwarning("无线连接", "设备未连接网络，请先连接网络")

    open_tcpip_button = tk.Button(main_frame, text="开启无线连接", command=open_tcpip)
    open_tcpip_button.place(x=270, y=47)

    def exit_tcpip():
        """关闭无线连接"""

        def tcpip_address():
            wifi_wlan = execute_command(f"{cmd_adb} shell ifconfig wlan0")
            ip_pattern = r'inet addr:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
            ip_match = re.search(ip_pattern, wifi_wlan)
            if ip_match:
                ip_wifi = ip_match.group(1)
                return ip_wifi
            else:
                logger.warning("IP地址未找到")
                return None

        execute_command(f"{cmd_adb} disconnect {tcpip_address()}:5555")
        logger.info("无线连接成功关闭")
        messagebox.showinfo("无线连接", "无线连接成功关闭")

    exit_tcpip_button = tk.Button(main_frame, text="关闭无线连接", command=exit_tcpip)
    exit_tcpip_button.place(x=380, y=47)

    def pull_lite():
        """导出标准版录屏和截图"""
        get_lite = lite_combobox.get().strip()
        logger.info(get_lite)
        if get_lite:
            if get_lite == "录屏文件":
                screenrecorder = execute_command(f"{cmd_adb} pull /sdcard/ScreenRecorder {paths()}")
                logger.info(screenrecorder)
                if "No such file or directory" in screenrecorder:
                    logger.warning("暂无录屏信息，请先录屏。")
                    messagebox.showwarning(title="录屏文件", message="暂无录屏信息，请先录屏。")
                else:
                    logger.info("录屏文件导出成功")
                    messagebox.showinfo(title="录屏文件",
                                        message="录屏文件导出成功，请在output文件中查看ScreenRecorder文件夹。")
            else:
                screenshots = execute_command(f"{cmd_adb} pull /sdcard/Screenshots {paths()}")
                logger.info(screenshots)
                if "No such file or directory" in screenshots:
                    logger.warning("暂无截图信息，请先截图。")
                    messagebox.showinfo(title="截图文件", message="暂无截图信息，请先截图。")
                else:
                    logger.info("截图文件导出成功")
                    messagebox.showinfo(title="截图文件",
                                        message="截图文件导出成功，请在output文件中查看Screenshots文件夹。")
        else:
            messagebox.showwarning(title="系统文件", message="请连接设备后选择需要导出的内容。")

    lite_combobox = ttk.Combobox(main_frame, values=["录屏文件", "截图文件"], state="readonly", width=9)
    lite_combobox.place(x=500, y=50)
    lite_button = tk.Button(main_frame, text="导出数据", command=pull_lite)
    lite_button.place(x=600, y=47)

    def packages():
        """获取应用包名-3、-f、-d、-s、-f -i -u"""
        cmd_pack = {
            "第三方程序": f"{cmd_adb} shell pm list packages -3",
            "已安装的程序": f"{cmd_adb} shell pm list packages",
            "包名及路径": f"{cmd_adb} shell pm list packages -f",
            "外部存储应用": f"{cmd_adb} shell pm list packages -d",
            "内部存储应用": f"{cmd_adb} shell pm list packages -e",
            "系统应用程序": f"{cmd_adb} shell pm list packages -s",
            "三方应用及路径": f"{cmd_adb} shell pm list packages -3 -f"
        }

        try:
            selected_option = combo.get().strip()
            logger.info(f"查询内容：{selected_option}")
            if selected_option in cmd_pack:
                cmd = cmd_pack[selected_option]
            else:
                logger.warning(f"无效的选择：{selected_option}")
                return
        except Exception as e:
            logger.error("Error0: {0}".format(e))
            messagebox.showerror("设备应用", f"Error:{e}")
            return
        process = subprocess.Popen(
            cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            shell=True,
            encoding="utf-8",
            bufsize=1,
            universal_newlines=True)
        output, error = process.communicate()
        if process.returncode == 0:
            logger.info(output)
            text_box.delete(1.0, tk.END)
            text_box.insert(tk.END, output)
        else:
            logger.error("Error1:", error)
            messagebox.showerror("设备应用", f"Error:{error}")

    combo = ttk.Combobox(main_frame, values=["第三方程序", "已安装的程序", "包名及路径", "外部存储应用", "内部存储应用",
                                             "系统应用程序", "三方应用及路径"])
    combo.place(x=150, y=288)
    button = tk.Button(main_frame, text="查询信息", command=packages)
    button.place(x=360, y=285)
    text_box = tk.Text(main_frame, width=90, height=10)
    text_box.place(x=20, y=320)

    def version_name():
        """版本号"""
        package_name = entry_name.get(1.0, tk.END).strip()
        logger.info(f"需要查询包名：{package_name}")

        def version_cmd(cmd):
            process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
            output, error = process.communicate()
            return output.decode('utf-8'), error.decode('utf-8')

        if package_name:
            output, error = version_cmd(f"{cmd_adb} shell dumpsys package {package_name} | findstr versionName")
            if error:
                logger.error(error)
                messagebox.showwarning("应用版本", error)
            else:
                if output == "":
                    logger.warning("没有找到对应的版本号，请检查输入包名是否正确！")
                    messagebox.showinfo("应用版本", "没有找到对应的版本号，请检查输入包名是否正确！")
                else:
                    logger.info(output)
                    messagebox.showinfo("应用版本", output)
        else:
            logger.warning("错误：请输入程序包名称")
            messagebox.showerror("应用版本", "错误：请输入程序包名称")

    entry_name = tk.Text(main_frame, width=30, height=2)
    entry_name.place(x=20, y=170)
    version_name_button = tk.Button(main_frame, text="查询版本号",
                                    command=lambda: threading.Thread(target=version_name).start())
    version_name_button.place(x=245, y=170)

    def pull_logcat():
        """导出日志"""
        logcat_name = entry_name.get(1.0, tk.END).strip()
        if not logcat_name:
            logcat_name = time_stamp()
        logger.info(f"日志名称：{logcat_name}")
        messagebox.showinfo("导出日志", "日志导出中，请稍后……")
        execute_command(f"{cmd_adb} logcat -v threadtime -d > {paths()}{logcat_name}.log")
        sleep(15)
        messagebox.showinfo("导出日志", "日志导出成功，请在output文件夹中查看")

    def pull_oslog():
        """导出OS系统日志"""
        logcat_name = entry_name.get(1.0, tk.END).strip()
        if not logcat_name:
            logcat_name = time_stamp()
        logger.info(f"系统日志名称：{logcat_name}")
        messagebox.showinfo("OS系统日志", "系统日志导出中，请稍后……")
        execute_command(f"{cmd_adb} bugreport {paths()}{logcat_name}_OS.zip")
        messagebox.showinfo("OS系统日志", "系统日志导出成功，请在output文件夹中查看")

    def clear_log():
        """清除日志"""
        execute_command(f"{cmd_adb} logcat -c")
        logger.info("日志清除成功！")
        messagebox.showinfo("日志清除", "日志清除成功！")

    def ip_address():
        """获取ip地址"""
        wifi_wlan = execute_command(f"{cmd_adb} shell ifconfig wlan0")
        ip_pattern = r'inet addr:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
        ip_match = re.search(ip_pattern, wifi_wlan)
        if ip_match:
            tcpip_address = ip_match.group(1)
            logger.info(f"设备IP地址：{tcpip_address}")
            messagebox.showinfo("设备IP地址", tcpip_address)
        else:
            wifi_eth = execute_command(f"{cmd_adb} shell ifconfig eth0")
            ip_pattern1 = r'inet addr:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
            ip_match1 = re.search(ip_pattern1, wifi_eth)
            if ip_match1:
                tcpip_address1 = ip_match1.group(1)
                logger.info(f"设备IP地址：{tcpip_address1}")
                messagebox.showinfo("设备IP地址", tcpip_address1)
            else:
                logger.error("未查询到IP地址，请检查设备是否正确连接wifi。")
                messagebox.showerror("设备IP地址", "未查询到IP地址，请检查设备是否正确连接wifi。")

    def query_package():
        """运行应用，获取应用包名"""
        text = execute_command(f"{cmd_adb} shell dumpsys window | findstr mCurrentFocus")
        pattern = r"u0 (.+?)\/"
        try:
            matches = re.findall(pattern, text)
            logger.info(f"当前运行应用包名：{matches[-1]}")
            messagebox.showinfo("当前运行应用", f"当前运行应用包名：{matches[-1]}")
        except IndexError as e:
            logger.warning("没有可运行的程序")
            messagebox.showerror("当前运行应用", "没有可运行的程序")

    pull_logcat_button = tk.Button(main_frame, text="导出日志",
                                   command=lambda: threading.Thread(target=pull_logcat).start())
    pull_logcat_button.place(x=330, y=170)
    pull_oslog_button = tk.Button(main_frame, text="OS系统日志",
                                  command=lambda: threading.Thread(target=pull_oslog).start())
    pull_oslog_button.place(x=405, y=170)
    clear_oslog_button = tk.Button(main_frame, text="清除日志",
                                   command=lambda: threading.Thread(target=clear_log).start())
    clear_oslog_button.place(x=500, y=170)
    pull_logcat_button = tk.Button(main_frame, text="查询设备IP", command=ip_address)
    pull_logcat_button.place(x=580, y=285)
    pull_logcat_button = tk.Button(main_frame, text="获取运行包名", command=query_package)
    pull_logcat_button.place(x=575, y=170)

    def delete_init():
        """删除init.json文件"""
        dete_init = execute_command(f"{cmd_adb} shell rm /sdcard/init.json")
        logger.info(dete_init)
        if not dete_init:
            logger.info("init.json文件，删除成功！")
            messagebox.showinfo("删除init文件", "init.json文件，删除成功！")
        else:
            logger.warning("没有找到init.json文件，请检查文件是否存在。")
            messagebox.showwarning("删除init文件", "没有找到init.json文件，请检查文件是否存在。")

    delete_init_button = tk.Button(main_frame, text="删除init文件",
                                   command=lambda: threading.Thread(target=delete_init).start())
    delete_init_button.place(x=582, y=206)

    def adb_pull():
        """导出文件"""
        device_path = device_path_entry.get("1.0", tk.END).strip()
        local_path = local_path_entry.get("1.0", tk.END).strip()
        if device_path and local_path:
            messagebox.showinfo("导出PULL", "导出中，请稍后……")
            pull = execute_command(f"{cmd_adb} pull {device_path} {local_path}")
            if "error" in pull:
                result = pull[pull.index("error") + len("error: "):]
                logger.error(f"导出失败：{result}")
                messagebox.showerror("导出PULL", f"导出失败：{result}")
            else:
                logger.info("导出成功")
                messagebox.showinfo("导出PULL", "导出成功")
        else:
            logger.warning("请确认设备和本地路径是否填写完整!")
            messagebox.showerror("导出PULL", "请确认设备和本地路径是否填写完整!")

    def adb_push():
        """导入文件"""
        device_path = device_path_entry.get("1.0", tk.END).strip()
        local_path = local_path_entry.get("1.0", tk.END).strip()
        if device_path and local_path:
            messagebox.showinfo("导入PUSH", "导入中，请稍后……")
            push = execute_command(f"{cmd_adb} push {local_path} {device_path}")
            if "error" in push:
                result = push[push.index("error") + len("error: "):]
                logger.error(f"导入失败：{result}")
                messagebox.showerror("导入PUSH", f"导入失败：{result}")
            else:
                logger.info("导入成功")
                messagebox.showinfo("导入PUSH", "导入成功")
        else:
            logger.warning("请确认设备和本地路径是否填写完整!")
            messagebox.showerror("导入PUSH", "请确认设备和本地路径是否填写完整!")

    def browse_local_folder():
        folder_path = filedialog.askdirectory()
        local_path_entry.delete(1.0, tk.END)
        local_path_entry.insert(tk.END, folder_path)

    def browse_local_file():
        file_path = filedialog.askopenfilename()
        local_path_entry.delete(1.0, tk.END)
        local_path_entry.insert(tk.END, file_path)

    device_path_label = tk.Label(main_frame, text="设备路径:")
    device_path_label.place(x=20, y=215)
    device_path_label.config(background="#87CEEB")
    device_path_label1 = tk.Label(main_frame, text="默认设备路径“/sdcard/”可修改")
    device_path_label1.place(x=390, y=212)
    device_path_label1.config(background="#87CEEB")
    device_path_entry = tk.Text(main_frame, width=40, height=2)
    device_path_entry.insert(tk.END, "/sdcard/")
    device_path_entry.place(x=90, y=210)
    local_path_label = tk.Label(main_frame, text="本地路径:")
    local_path_label.place(x=20, y=250)
    local_path_label.config(background="#87CEEB")
    local_path_entry = tk.Text(main_frame, width=40, height=2)
    local_path_entry.place(x=90, y=245)
    browse_file_button = tk.Button(main_frame, text="选择文件", command=browse_local_file)
    browse_file_button.place(x=385, y=245)
    browse_folder_button = tk.Button(main_frame, text="选择文件夹", command=browse_local_folder)
    browse_folder_button.place(x=453, y=245)
    pull_button = tk.Button(main_frame, text="导出Pull", command=lambda: threading.Thread(target=adb_pull).start())
    pull_button.place(x=533, y=245)
    push_button = tk.Button(main_frame, text="导入Push", command=lambda: threading.Thread(target=adb_push).start())
    push_button.place(x=597, y=245)

    def resting_screen():
        """系统灭屏时间查询"""
        mp = execute_command(f"{cmd_adb} shell dumpsys rokid_display").splitlines()
        try:
            for item in mp:
                if item.startswith('psensor off timeout:'):
                    # 提取冒号后面的数值
                    psensor_timeout = int(item.split(': ')[1])
                    break
            print(psensor_timeout)
            logger.info(f"灭屏时间为：{psensor_timeout / 1000}秒")
            messagebox.showinfo(title="灭屏时间", message=f"灭屏时间为：{psensor_timeout / 1000} 秒")
        except ValueError as e:
            logger.warning("未查询到灭屏超时时间")
            messagebox.showwarning(title="灭屏时间", message="未查询到灭屏超时时间")

    mp_button = tk.Button(main_frame, text="灭屏时间", command=resting_screen)
    mp_button.place(x=470, y=286)


def show_common():
    """其他功能"""
    reset_frame()

    def scrcpy_id():
        """检索显示 ID 列表"""
        try:
            sid = execute_command(f"{paths('bin')}scrcpy.exe -s {cmd_device} --list-displays")
            display_ids = re.findall(r"--display-id=(\d+)", sid)
            logger.info(f"显示ID：{display_ids[1]}")
            return display_ids[1]
        except Exception as e:
            logger.error(f"设备与眼镜未连接,{e}")
            scrcpy_id_text.delete(1.0, tk.END)
            scrcpy_id_text.insert(tk.END, "设备与眼镜未连接，或者请插拔后重试！")
            return None

    def show_scrcpy_id():
        """查询眼镜id"""
        scrcpy_ids = scrcpy_id()
        logger.info(f"眼镜id：{scrcpy_ids}")
        if scrcpy_ids:
            scrcpy_id_text.delete(1.0, tk.END)
            scrcpy_id_text.insert(tk.END, scrcpy_ids)
        else:
            scrcpy_id_text.delete(1.0, tk.END)
            scrcpy_id_text.insert(tk.END, "请检查眼镜和设备是否正确连接并且开启无线连接！")
            logger.warning("请检查眼镜和设备是否正确连接并且开启无线连接！")

    def screen():
        """掉用scrcpy实现双屏投屏"""
        try:
            execute_command(f"{paths('bin')}scrcpy.exe -s {cmd_device} --display-id {scrcpy_id()}")
        except Exception as e:
            logger.error(f"双屏投屏异常：{e}")
            return None

    def glass_screen_half():
        """掉用scrcpy实现眼镜单屏投屏"""
        try:
            execute_command(f"{paths('bin')}scrcpy.exe -s {cmd_device} --display-id {scrcpy_id()} --crop=1920:1200:0:0")
        except Exception as e:
            logger.error(f"单屏投屏异常：{e}")
            return None

    def device_screen():
        """掉用scrcpy实现设备投屏"""
        try:
            execute_command(f"{paths('bin')}scrcpy.exe -s {cmd_device}")
        except Exception as e:
            logger.error(e)
            return None

    glass_id_text = tk.Label(main_frame, text="眼镜信息：")
    glass_id_text.place(x=20, y=15)
    glass_id_text.config(background="#87CEEB")
    # 添加文本框用于显示设备ID
    scrcpy_id_text = tk.Text(main_frame, width=30, height=2)
    scrcpy_id_text.place(x=85, y=10)
    # 添加按钮
    scrcpy_id_button = tk.Button(main_frame, text='眼镜ID', command=show_scrcpy_id)
    scrcpy_id_button.place(x=310, y=10)
    # 眼镜投屏功能，异步实现
    screen_button1 = tk.Button(main_frame, text='眼镜投屏',
                               command=lambda: threading.Thread(target=glass_screen_half).start())
    screen_button1.place(x=377, y=10)
    screen_button2 = tk.Button(main_frame, text='眼镜投屏2', command=lambda: threading.Thread(target=screen).start())
    screen_button2.place(x=455, y=10)
    # 设备投屏功能，异步实现
    screen_button2 = tk.Button(main_frame, text='终端投屏',
                               command=lambda: threading.Thread(target=device_screen).start())
    screen_button2.place(x=540, y=10)

    def scrcpy_record_half():
        """使用scrcpy实现单屏投屏内容录制"""
        record_video = scrcpy_record_name_entry.get(1.0, tk.END).strip()
        if not record_video:
            record_video = time_stamp()
        try:
            execute_command(
                f"{paths('bin')}scrcpy.exe -s {cmd_device} --display-id {scrcpy_id()} --crop=1920:1200:0:0 --record {paths()}{record_video}.mp4")
        except TypeError as e:
            logger.error("出错了{}".format(e))
            scrcpy_record_name_entry.delete(1.0, tk.END)
            scrcpy_record_name_entry.insert(tk.END, "请检查眼镜和设备是否正确连接并且开启无线连接！")

    def scrcpy_record():
        """使用scrcpy实现双屏投屏内容录制"""
        record_video1 = scrcpy_record_name_entry.get(1.0, tk.END).strip()
        if not record_video1:
            record_video1 = time_stamp()
        try:
            execute_command(
                f"{paths('bin')}scrcpy.exe -s {cmd_device} --display-id {scrcpy_id()} --record {paths()}{record_video1}.mp4")
        except TypeError as e:
            logger.error("出错了{}".format(e))
            scrcpy_record_name_entry.delete(1.0, tk.END)
            scrcpy_record_name_entry.insert(tk.END, "请检查眼镜和设备是否正确连接并且开启无线连接！")

    def terminal_screen():
        """终端录屏"""
        record_video2 = scrcpy_record_name_entry.get(1.0, tk.END).strip()
        if not record_video2:
            record_video2 = time_stamp()
        try:
            execute_command(
                f"{paths('bin')}scrcpy.exe -s {cmd_device} --display-id 0 --record {paths()}{record_video2}.mp4")
        except TypeError as e:
            logger.error("出错了{}".format(e))
            scrcpy_record_name_entry.delete(0, tk.END)
            scrcpy_record_name_entry.insert(tk.END, "请检查眼镜和设备是否正确连接并且开启无线连接！")

    scrcpy_record_name = tk.Label(main_frame, text="保存名称:")
    scrcpy_record_name.place(x=20, y=55)
    scrcpy_record_name.config(background="#87CEEB")
    scrcpy_record_name_entry = tk.Text(main_frame, width=30, height=2)
    scrcpy_record_name_entry.place(x=85, y=50)
    scrcpy_record_button = tk.Button(main_frame, text="录制单屏眼镜",
                                     command=lambda: threading.Thread(target=scrcpy_record_half).start())
    scrcpy_record_button.place(x=310, y=50)
    scrcpy_record_button = tk.Button(main_frame, text="录制双屏眼镜",
                                     command=lambda: threading.Thread(target=scrcpy_record).start())
    scrcpy_record_button.place(x=413, y=50)
    scrcpy_record_button2 = tk.Button(main_frame, text="录制设备终端",
                                      command=lambda: threading.Thread(target=terminal_screen).start())
    scrcpy_record_button2.place(x=515, y=50)

    def start_pack_name():
        """启动应用包名"""
        pack_name = start_name_name_entry.get(1.0, tk.END).strip()
        if pack_name:
            start_pack = execute_command(
                f"{cmd_adb} shell am start -n {pack_name}/com.rokid.uxrunityplugin.UXRActivity")
            logger.info(start_pack)
        else:
            logger.warning("请正确输入需要启动的3D应用包名")
            messagebox.showwarning(title="启动应用", message="请正确输入需要启动的3D应用包名")

    def close_pack_name():
        """关闭启动的应用"""
        pack_name = start_name_name_entry.get(1.0, tk.END).strip()
        if pack_name:
            execute_command(f"{cmd_adb} shell am force-stop {pack_name}")
            logger.info(f"应用 {pack_name} 关闭成功！")
        else:
            logger.warning("请正确输入需要关闭的应用包名")
            messagebox.showwarning(title="关闭应用", message="请正确输入需要关闭的应用包名")

    start_name = tk.Label(main_frame, text="应用包名:")
    start_name.place(x=20, y=105)
    start_name.config(background="#87CEEB")
    start_name_name_entry = tk.Text(main_frame, width=30, height=2)
    start_name_name_entry.place(x=85, y=100)
    start_name_button = tk.Button(main_frame, text="启动应用", command=start_pack_name)
    start_name_button.place(x=310, y=100)
    start_name1_button = tk.Button(main_frame, text="关闭应用", command=close_pack_name)
    start_name1_button.place(x=390, y=100)

    combo_key = {
        "打开相机": f"{cmd_adb} shell am start -n com.android.camera2/com.android.camera.CameraActivity",
        "打开相册": f"{cmd_adb} shell am start -n com.android.gallery3d/com.android.gallery3d.app.GalleryActivity",
        "开启蓝牙": f"{cmd_adb} shell svc bluetooth enable",
        "关闭蓝牙": f"{cmd_adb} shell svc bluetooth disable",
        "蓝牙状态": f"{cmd_adb} shell dumpsys bluetooth_manager",
        "电池信息": f"{cmd_adb} shell dumpsys battery"
    }

    def on_combobox_selected(event):
        """获取选中的值"""
        selected_value = combo.get()
        logger.info(f"选中的值: {selected_value}")
        vaule = combo_key[selected_value]

        def execute_adb_command_in_thread(vaules):
            if selected_value in ["打开相机", "打开相册"]:
                execute_command(vaules)
                device_screen()
            elif selected_value in ["开启蓝牙", "关闭蓝牙"]:
                execute_command(vaules)
                logger.info(f"成功{selected_value}")
                messagebox.showinfo(title="蓝牙开关", message=f"成功{selected_value}")
            elif selected_value == "蓝牙状态":
                _status = execute_command(vaules)
                status_list = _status.splitlines()[1:5]
                status = "\n".join(status_list).replace("enabled:", "是否启用:").replace("state:", "蓝牙状态:"). \
                    replace("address:", "蓝牙地址:").replace("name:", "蓝牙名称:")
                logger.info(f"蓝牙信息：{status}")
                messagebox.showinfo(title="蓝牙信息", message=status)
            else:
                _status = execute_command(vaules).split()[25:38]
                # print(_status)
                status = {
                    "1": "未知状态",
                    "2": "充电中",
                    "3": "放电中",
                    "4": "未在充电",
                    "5": "电池充满"
                }

                health = {
                    "1": "未知健康状况",
                    "2": "良好",
                    "3": "过热",
                    "4": "电池没电，无法再充电",
                    "5": "过电压",
                    "6": "未指明的故障",
                    "7": "电池过冷"
                }

                battery_info = {
                    "电池状态": status[_status[0]],
                    "电池状况": health[_status[2]],
                    "电池电量": f"{_status[6]}%",
                    "电池电压": f"{int(_status[-3]) / 1000}V",
                    "电池温度": f"{int(_status[-1]) / 10}℃"
                }
                battery_info_string = "电池状态: {电池状态} \n电池状况: {电池状况} \n电池电量: {电池电量} \n电池电压: " \
                                      "{电池电压} \n电池温度: {电池温度}".format(**battery_info)
                logger.info(f"电池信息：{battery_info}")
                messagebox.showinfo(title="电池信息", message=battery_info_string)

        thread = threading.Thread(target=execute_adb_command_in_thread, args=(vaule,))
        thread.start()

    options = ["打开相机", "打开相册", "开启蓝牙", "关闭蓝牙", "蓝牙状态", "电池信息"]
    combo = ttk.Combobox(main_frame, values=options, width=10)
    combo.place(x=505, y=103)
    combo.bind("<<ComboboxSelected>>", on_combobox_selected)

    def wifi_status():
        def show_wifi_status():
            """查看wifi状态"""
            fh = execute_command(f"{cmd_adb} shell cmd wifi status")
            logger.info(fh)
            return fh

        if show_wifi_status():
            wifi_text.delete(1.0, tk.END)
            wifi_text.insert(tk.END, show_wifi_status())
        else:
            wifi_text.delete(1.0, tk.END)
            wifi_text.insert(tk.END, show_wifi_status())

    def get_wifi_ssid(ssid="test"):
        """获取已经保存的WiFi⽹络ID"""
        ai = []
        get_wifi = execute_command(f"{cmd_adb} shell cmd wifi get-network-id '{ssid}'")
        logger.info(f"查询wifi的ID值：{get_wifi}")
        if "命令执行出错" in get_wifi:
            get_wifi_list = execute_command(f"{cmd_adb} shell cmd wifi list-networks")
            for wifi in get_wifi_list.splitlines():
                if ssid in wifi:
                    ai.extend(wifi.split())
                    break
            logger.info(ai)
            return ai
        return get_wifi

    def wifi_list_networks():
        """获取所有已保存的Wifi⽹络ID列表"""
        fh = execute_command(f"{cmd_adb} shell cmd wifi list-networks")
        logger.info(fh)
        if fh:
            wifi_text.delete(1.0, tk.END)
            wifi_text.insert(tk.END, fh)
        else:
            wifi_text.delete(1.0, tk.END)
            wifi_text.insert(tk.END, fh)

    def delete_wifi():
        """删除已经保存的网络 wifi_name=test"""
        wifi_name = wifi_delete_entry.get(1.0, tk.END).strip()
        logger.info(f"需要删除的wifi名称：{wifi_name}")
        if wifi_name:
            wifi_id = get_wifi_ssid(ssid=wifi_name)[0]
            logger.info(f"待删除wifiID：{wifi_id}")
            fh = execute_command(f"{cmd_adb} shell cmd wifi forget-network {wifi_id}")
            logger.info(fh)
            wifi_text.delete(1.0, tk.END)
            wifi_text.insert(tk.END, fh)
        else:
            wifi_text.delete(1.0, tk.END)
            wifi_text.insert(tk.END, "请在“删除wifi”输入框，输入需要删除的wifi名称！")

    def open_wifi():
        """打开wifi"""
        fh = execute_command(f"{cmd_adb} shell cmd wifi set-wifi-enabled enabled")
        logger.info(f"openwifi:{fh}")
        wifi_text.delete(1.0, tk.END)
        wifi_text.insert(tk.END, "wifi开启成功")

    def close_wifi():
        """关闭wifi"""
        fh = execute_command(f"{cmd_adb} shell cmd wifi set-wifi-enabled disabled")
        logger.info(f"closewif:{fh}")
        wifi_text.delete(1.0, tk.END)
        wifi_text.insert(tk.END, "wifi关闭成功")

    def add_wifi():
        """添加wifi ssid="test", pwd="123456"""
        ssid = wifi_name_entry.get(1.0, tk.END).strip()
        pwd = wifi_pwd_entry.get(1.0, tk.END).strip()
        if ssid and pwd:
            fh = execute_command(f"{cmd_adb} shell cmd wifi add-network '{ssid}' wpa2 '{pwd}'")
            logger.info(fh)
            wifi_text.delete(1.0, tk.END)
            wifi_text.insert(tk.END, fh)
        else:
            wifi_text.delete(1.0, tk.END)
            wifi_text.insert(tk.END, "请检查账号密码是否输入正确！")

    def connect_wifi():
        """开启wifi后，连接wifi ssid="test", pwd="123456"""
        ssid = wifi_name_entry.get(1.0, tk.END).strip()
        pwd = wifi_pwd_entry.get(1.0, tk.END).strip()
        if ssid and pwd:
            open_wifi()
            sleep(2)
            fh = execute_command(f"{cmd_adb} shell cmd wifi connect-network '{ssid}' wpa2 '{pwd}'")
            logger.info(fh)
            wifi_text.delete(1.0, tk.END)
            wifi_text.insert(tk.END, fh)
        else:
            wifi_text.delete(1.0, tk.END)
            wifi_text.insert(tk.END, "请确认账号密码是否输入正确！")

    def segno_wifi_qr():
        """生成wifi二维码"""
        name = wifi_name_entry.get(1.0, tk.END).strip()
        pwd = wifi_pwd_entry.get(1.0, tk.END).strip()
        if name and pwd:
            logger.info(f"输入的ssid：{name}，密码：{pwd}")
            qr_code_message = f"WIFI:S:{name};T:WPA;P:{pwd};H:false;;"
            qr = segno.make(qr_code_message)
            qr.save(f"{paths()}{time_stamp()}.png", scale=15)
            messagebox.showinfo(title="Wifi 二维码", message="wifi二维码生成成功，请在output文件夹中查看。")
        else:
            logger.warning("请输入正确的wifi名称和密码")
            messagebox.showinfo(title="Wifi 二维码", message="请输入正确的wifi名称和密码。")

    wifi_ssid_name = tk.Label(main_frame, text="wifi名称:")
    wifi_ssid_name.place(x=20, y=145)
    wifi_ssid_name.config(background="#87CEEB")
    wifi_name_entry = tk.Text(main_frame, width=30, height=2)
    wifi_name_entry.place(x=85, y=140)
    wifi_ssid_pwd = tk.Label(main_frame, text="wifi密码:")
    wifi_ssid_pwd.place(x=325, y=145)
    wifi_ssid_pwd.config(background="#87CEEB")
    wifi_pwd_entry = tk.Text(main_frame, width=30, height=2)
    wifi_pwd_entry.place(x=385, y=140)
    delete_wifi_ssid_name = tk.Label(main_frame, text="删除wifi:")
    delete_wifi_ssid_name.place(x=20, y=225)
    delete_wifi_ssid_name.config(background="#87CEEB")
    wifi_delete_entry = tk.Text(main_frame, width=30, height=2)
    wifi_delete_entry.place(x=85, y=220)
    wifi_text = tk.Text(main_frame, width=90, height=13)
    wifi_text.place(x=20, y=270)
    wifi_status_button = tk.Button(main_frame, text="查询wifi状态", command=wifi_status)
    wifi_status_button.place(x=390, y=220)
    generate_wifi_qr_button = tk.Button(main_frame, text="生成wifi图片", command=segno_wifi_qr)
    generate_wifi_qr_button.place(x=20, y=180)
    open_wifi_button = tk.Button(main_frame, text="打开wifi", command=open_wifi)
    open_wifi_button.place(x=165, y=180)
    close_wifi_button = tk.Button(main_frame, text="关闭wifi", command=close_wifi)
    close_wifi_button.place(x=295, y=180)
    add_wifi_button = tk.Button(main_frame, text="添加wifi", command=add_wifi)
    add_wifi_button.place(x=420, y=180)
    connect_wifi_button = tk.Button(main_frame, text="连接wifi", command=connect_wifi)
    connect_wifi_button.place(x=545, y=180)
    delete_wifi_button = tk.Button(main_frame, text="删除wifi", command=delete_wifi)
    delete_wifi_button.place(x=320, y=220)
    wifi_list_networks_button = tk.Button(main_frame, text="查询全部wifi网络ID", command=wifi_list_networks)
    wifi_list_networks_button.place(x=485, y=220)


def show_system():
    """系统功能"""
    reset_frame()

    def getprop():
        """获取系统版本号、主机SN号、眼镜SN号"""
        cmd_mapping = {
            "系统构建版本号": f"{cmd_adb} shell getprop ro.build.version.incremental",
            "设备SN号": f"{cmd_adb} shell getprop ro.serialno",
            "眼镜SN号": f"{cmd_adb} shell getprop persist.rokid.glass.sn",
            "UXR服务号": f"{cmd_adb} shell getprop | findstr rokid.xrbis.version",
            "系统打包类型": f"{cmd_adb} shell getprop | findstr ro.build.type",
            "Android版本号": f"{cmd_adb} shell getprop ro.build.version.release",
            "Android SDK版本号": f"{cmd_adb} shell getprop ro.build.version.sdk",
            "设备厂商名称": f"{cmd_adb} shell getprop ro.product.brand",
            "设备型号": f"{cmd_adb} shell getprop ro.product.model",
            "安全补丁时间": f"{cmd_adb} shell getprop ro.build.version.security_patch",
            "硬件名称": f"{cmd_adb} shell getprop ro.hardware",
            "主板平台": f"{cmd_adb} shell getprop ro.board.platform",
            "自定义设备名称": f"{cmd_adb} shell getprop persist.sys.device_name",
            "设备默认名称": f"{cmd_adb} shell getprop ro.product.marketname",
            "系统构建日期": f"{cmd_adb} shell getprop ro.build.date.utc",
            "系统相关属性": f"{cmd_adb} shell getprop",
            "系统版本ID": f"{cmd_adb} shell getprop ro.build.id",
            "系统版本TAG": f"{cmd_adb} shell getprop ro.build.tags",
            "设备类型": f"{cmd_adb} devices",
            "CPU架构": f"{cmd_adb} shell getprop ro.product.cpu.abi"
        }
        try:
            _select = select_getprop.get()
            logger.info(_select)
            if _select in cmd_mapping:
                cmd = cmd_mapping[_select]
            else:
                logger.warning(f"无效的选择：{_select}")
                return
        except Exception as e:
            logger.error("Error:", e)
            messagebox.showwarning("系统信息", str(e))
            return
        process = subprocess.Popen(
            cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            shell=True,
            encoding="utf-8",
            bufsize=1,
            universal_newlines=True)
        output, error = process.communicate()
        if process.returncode == 0:
            if _select == "系统构建日期":
                time_str_s = ti.strftime("%Y-%m-%d %H:%M:%S", ti.localtime(int(output)))
                logger.info(time_str_s)
                getprop_text_box.delete(1.0, tk.END)
                getprop_text_box.insert(tk.END, time_str_s)
            elif _select == "系统打包类型":
                os_lx = output.split(":")[1].strip()
                logger.info(os_lx)
                if os_lx == "[user]":
                    os_lx = "用户user版本"
                elif os_lx == "[userdebug]":
                    os_lx = "root版本"
                else:
                    os_lx = "未知版本"
                getprop_text_box.delete(1.0, tk.END)
                getprop_text_box.insert(tk.END, os_lx)
            elif _select == "设备类型":
                sblx = cmd_device[8:10]
                if sblx == "32" or sblx == "41":
                    sblx = "当前设备类型为DVT"
                    logger.info(f"{cmd_device}为DVT类型")
                elif int(sblx) >= 48:
                    sblx = "当前设备类型为PVT"
                    logger.info(f"{cmd_device}为PVT类型")
                else:
                    sblx = "未知设备类型"
                    logger.info(f"{cmd_device}未知设备类型")
                getprop_text_box.delete(1.0, tk.END)
                getprop_text_box.insert(tk.END, sblx)
            else:
                logger.info(output)
                getprop_text_box.delete(1.0, tk.END)
                getprop_text_box.insert(tk.END, output)
        else:
            logger.error("Error1:", error)
            messagebox.showerror(title="系统信息", message=f"没有找到相关信息{error}")

    # def open_settings():
    #     """打开系统设设置"""
    #     subprocess.check_output(f"{cmd_adb} shell am start -a android.settings.SETTINGS", shell=True,
    #                             stderr=subprocess.STDOUT, text=True)
    #     subprocess.Popen([f"{paths('bin')}scrcpy.exe", "-s", cmd_device, "--display-id", "0"])
    #     return "进入系统设置页面"

    def open_settings():
        """打开系统设置，并隐藏命令行窗口"""
        # Windows下隐藏命令行窗口
        creation_flags = 0
        if os.name == 'nt':
            creation_flags = subprocess.CREATE_NO_WINDOW
        # 启动投屏，隐藏窗口
        scrcpy_proc = subprocess.Popen(
            [f"{paths('bin')}scrcpy.exe", "-s", cmd_device, "--display-id", "0"],
            creationflags=creation_flags
        )
        # 使用ADB命令打开Android设置
        adb_output = subprocess.check_output(
            f"{cmd_adb} shell am start -a android.settings.SETTINGS",
            shell=True, stderr=subprocess.STDOUT, text=True
        )
        return "进入系统设置页面"

    def exit_settings():
        """退出系统设置，回到后台"""
        subprocess.check_output(f"{cmd_adb} shell input keyevent KEYCODE_HOME", shell=True, stderr=subprocess.STDOUT,
                                text=True)
        os.popen("taskkill /IM scrcpy.exe")
        return "退出设置"

    def device_shutdown():
        """关机"""
        logger.info("设备已经关机")
        execute_command(f"{cmd_adb} reboot -p")

    def device_reboot():
        """重启设备"""
        logger.info("设备重启中，请稍后……")
        execute_command(f"{cmd_adb} reboot")

    "查询系统版本及相关SN号"
    select_getprop = ttk.Combobox(main_frame,
                                  values=["系统构建版本号", "设备SN号", "眼镜SN号", "UXR服务号", "系统打包类型",
                                          "设备类型", "系统构建日期", "Android版本号", "Android SDK版本号",
                                          "设备厂商名称", "设备型号", "安全补丁时间", "硬件名称", "主板平台",
                                          "CPU架构", "自定义设备名称", "设备默认名称", "系统相关属性"],
                                  state="readonly")
    select_getprop.place(x=20, y=20)
    getprop_button = tk.Button(main_frame, text="获取信息", command=getprop)
    getprop_button.place(x=192, y=17)
    getprop_text_box = tk.Text(main_frame, width=85, height=10)
    getprop_text_box.place(x=20, y=60)
    open_settings_button = tk.Button(main_frame, text="系统设置", command=open_settings)
    open_settings_button.place(x=272, y=17)
    exit_settings_button = tk.Button(main_frame, text="退出设置返回首页", command=exit_settings)
    exit_settings_button.place(x=352, y=17)
    device_reboot_button = tk.Button(main_frame, text="设备重启",
                                     command=lambda: threading.Thread(target=device_reboot).start())
    device_reboot_button.place(x=480, y=17)
    device_shutdown_button = tk.Button(main_frame, text="设备关机",
                                       command=lambda: threading.Thread(target=device_shutdown).start())
    device_shutdown_button.place(x=560, y=17)

    # 童锁设置功能
    ock_dict = {
        "Home键": "3",
        "音量增加键": "24",
        "音量减少键": "25",
        "电源键": "26"
    }

    def generate_command(app_name, selection):
        selected_keys = [ock_dict[key] for key in selection]
        command = execute_command(
            f"{cmd_adb} shell settings put global sys_key_locked_app {app_name}:{':'.join(selected_keys)}")
        logger.info(command)
        return command

    def shield_button():
        app_name = app_name_entry.get().strip()
        logger.info(f"屏蔽按键包名：{app_name}")
        selection = [check_var.get() for check_var in check_vars]
        selected_keys = [key for key, checked in zip(ock_dict.keys(), selection) if checked]
        logger.info(f"屏蔽按键：{selected_keys}")
        if not bool(app_name) or not bool(selected_keys):
            messagebox.showwarning("童锁设置", "请正确输入包名并选择需要设置童锁的按键！")
        else:
            generate_command(app_name, selected_keys)
            messagebox.showwarning("童锁设置", f"包名：{app_name} 的童锁设置成功！")

    app_name_label = tk.Label(main_frame, text="应用包名:")
    app_name_label.place(x=20, y=205)
    app_name_label.config(background="#87CEEB")
    app_name_entry = tk.Entry(main_frame)
    app_name_entry.place(x=80, y=205)
    check_vars = []
    for i, key in enumerate(ock_dict.keys()):
        check_var = tk.IntVar()
        check_vars.append(check_var)
        chk = tk.Checkbutton(main_frame, text=key, variable=check_var, bg='#87CEEB')
        chk.place(x=20, y=230 + i * 20)
    shield_button_an = tk.Button(main_frame, text="设置童锁", command=shield_button)
    shield_button_an.place(x=165, y=160 + len(ock_dict) * 30)

    def not_shield_button():
        """解除应用童锁屏蔽"""
        app_name = app_name_entry.get().strip()
        logger.info(f"解除童锁包名：{app_name}")
        if not bool(app_name):
            messagebox.showwarning("童锁释放", "请正确输入需要释放童锁的包名！")
        else:
            execute_command(f"{cmd_adb} shell settings put global sys_key_locked_app {app_name}")
            messagebox.showinfo("童锁释放", f"包名：{app_name} 的童锁释放成功！")

    not_shield_button_an = tk.Button(main_frame, text="释放童锁", command=not_shield_button)
    not_shield_button_an.place(x=165, y=120 + len(ock_dict) * 30)

    def get_shield_button():
        """获取童锁参数设置信息"""
        shield_lock = []
        lock_dict = {
            "3": "Home键",
            "24": "音量增加键",
            "25": "音量减少键",
            "26": "电源键"
        }
        default_lock = "运行应用暂未查询到童锁按键设置"
        lock = execute_command(f"{cmd_adb} shell settings get global sys_key_locked_app")
        numbers = re.findall(r':(\d+)', lock)
        logger.info("查询童锁设置：{}".format(numbers))
        if numbers:
            for i in numbers:
                if i in lock_dict:
                    shield_lock.append(lock_dict[i])
                else:
                    pass
        else:
            shield_lock.append(default_lock)
        logger.info("童锁按键：{}".format(shield_lock))
        get_shield_button_entry.delete(1.0, tk.END)
        get_shield_button_entry.insert(tk.END, "\n".join(shield_lock))

    get_shield_button_an = tk.Button(main_frame, text="查询童锁",
                                     command=lambda: threading.Thread(target=get_shield_button).start())
    get_shield_button_an.place(x=50, y=320)
    get_shield_button_entry = tk.Text(main_frame, width=30, height=7)
    get_shield_button_entry.place(x=20, y=355)

    def temporary_desktop():
        """临时回到launcher桌面"""
        execute_command(f"{cmd_adb} shell am broadcast -a android.app.LauncherE.action.LAUNCHER")

    temporary_desktop_button = tk.Button(main_frame, text="回到桌面",
                                         command=lambda: threading.Thread(target=temporary_desktop).start())
    temporary_desktop_button.place(x=145, y=320)

    def psensor_sleep_timeout():
        """息屏时间设置"""
        number = brightness_entry.get().strip()
        logger.info(f"设置息屏值：{number}")
        if not number:
            number = 30
        execute_command(f"{cmd_adb} shell settings put system psensor_sleep_timeout {int(number) * 1000}")
        messagebox.showinfo(title="屏幕息屏值", message=f"设置息屏时间{number}秒成功！")

    def brightness():
        """屏幕亮度设置"""
        number = brightness_entry.get().strip()
        logger.info(f"设置亮度值：{number}")
        if not number:
            number = 50
        execute_command(f"{cmd_adb} shell settings put system screen_brightness {number}")
        messagebox.showinfo(title="屏幕亮度", message=f"设置亮度值{number}成功！")

    brightness_label = tk.Label(main_frame, text="设置数值:")
    brightness_label.place(x=270, y=210)
    brightness_label.config(background="#87CEEB")
    brightness_entry = tk.Entry(main_frame)
    brightness_entry.place(x=330, y=210)
    brightness_button = tk.Button(main_frame, text="设置亮度", command=brightness)
    brightness_button.place(x=485, y=205)
    psensor_sleep_timeout_button = tk.Button(main_frame, text="息屏时间", command=psensor_sleep_timeout)
    psensor_sleep_timeout_button.place(x=560, y=205)

    def extract_apk():
        """
        提取已经安装的apk
        packs：需要提取的应用包名
        path：本地导出路径，默认在output文件夹下
        """
        bdlj = paths()
        packs = extract_apk_entry.get().strip()
        logger.info(f"提取包名：{packs}")
        if not bool(packs):
            messagebox.showwarning("APK提取", "请输入系统已经安装的正确包名")
        else:
            messagebox.showinfo("APK提取", "APK提取中请稍后……")
            sdcard = execute_command(f"{cmd_adb} shell pm path {packs}")
            logger.info(sdcard)
            sleep(0.3)
            execute_command(f"{cmd_adb} pull {sdcard[8:].strip()} {bdlj}")
            messagebox.showinfo("APK提取", f"{packs} 提取成功，请在output文件夹下查看")

    extract_apk_label = tk.Label(main_frame, text="待提取应用包名:")
    extract_apk_label.place(x=280, y=245)
    extract_apk_label.config(background="#87CEEB")
    extract_apk_entry = tk.Entry(main_frame)
    extract_apk_entry.place(x=380, y=245)
    extract_apk_button = tk.Button(main_frame, text="提取APK",
                                   command=lambda: threading.Thread(target=extract_apk).start())
    extract_apk_button.place(x=560, y=240)

    def os_flashing_edl():
        """OS系统刷机前置脚步"""
        for number in initialize():
            execute_command(f"adb.exe -s {number} reboot edl")
        messagebox.showinfo("OS系统刷机", "所有设备已就绪,可以刷机")
        logger.info("所有设备已就绪,可以刷机")

    os_flashing_buuton = tk.Button(main_frame, text="系统刷机前置", command=os_flashing_edl)
    os_flashing_buuton.place(x=555, y=280)

    def computer_ip():
        """查询电脑IP"""
        try:
            if "nt" == os.name:
                hostname = socket.gethostbyname(socket.gethostname())
            else:  # macOS
                hostname = execute_command("ifconfig | grep 'inet ' | grep -v '127.0.0.1' | awk '{print $2}'")
            logger.info(f"电脑IP：{hostname}")
            computer_ip_text.delete(1.0, tk.END)
            computer_ip_text.insert(tk.END, f"电脑IP地址：{hostname}")
        except Exception as e:
            logger.error(f'无法获取IP地址: {e}')
            computer_ip_text.delete(1.0, tk.END)
            computer_ip_text.insert(tk.END, f"请检查电脑网络是否正确连接 \n {e}")

    computer_ip_button = tk.Button(main_frame, text="电脑IP地址",
                                   command=lambda: threading.Thread(target=computer_ip).start())
    computer_ip_button.place(x=465, y=280)
    computer_ip_text = tk.Text(main_frame, width=25, height=2)
    computer_ip_text.place(x=270, y=280)

    def open_adb_broadcast():
        """开启广播"""
        execute_command(f"{cmd_adb} shell am broadcast -a android.intent.customize.action.JUDGE_BEFORE_UPDATE")
        # sleep(1)
        logger.info("开启广播成功")
        return True

    def setup_adb_forward():
        """设置端口转发"""
        try:
            execute_command(f"{cmd_adb} forward tcp:8000 tcp:9000")
            logger.info("端口转发设置完成")
            return True
        except Exception as e:
            logger.error(f"设置端口转发失败：{e}")
            return False

    def start_client_thread():
        """开启客户端线程"""

        def run():
            """运行"""
            if not setup_adb_forward():
                logger.error("设置端口转发失败")
            try:
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                s.connect(('127.0.0.1', 8000))
                open_adb_broadcast()
                while True:
                    data = s.recv(1024)
                    if not data:
                        break
                    output_data = eval(data.decode('utf-8'))
                    logger.info(f"接收到：{output_data}")
                    try:
                        update_progress_bar(output_data["param_progress"])
                    except:
                        if output_data.get("msgCmd") == "cmd_show_need_reboot":
                            adb_reboot()
                            logger.info("升级成功")
                            break
                        elif output_data.get("msgCmd") == "cmd_show_upgrade_failed":
                            logger.warning(f"升级失败，不能降级操作！\n {output_data.get('param_info')}")
                            messagebox.showerror("OTA升级", f"升级失败，不能降级操作！\n {output_data.get('param_info')}")

            except Exception as e:
                logger.error(f"发生错误：{e}")
                return f"发生错误：{e}"
            finally:
                s.close()
                return "更新完成"

        thread = threading.Thread(target=run)
        thread.start()

    def update_progress_bar(number):
        """更新进度条"""
        progress_bar['value'] = number
        progress_percent.set(f"{number}%")
        miao = eval(f"{time() - start_time:.2f}")
        minutes, second = divmod(int(miao), 60)
        elapsed_time_label.configure(text=f"耗时：{minutes:.0f}分{second:.0f}秒")
        main_frame.update_idletasks()
        logger.info(f"耗时：{minutes:.0f}分{second:.0f}秒")

    def adb_reboot():
        """重启设备"""
        execute_command(f"{cmd_adb} reboot")
        return True

    progress_bar = ttk.Progressbar(main_frame, orient='horizontal', length=200, mode='determinate')
    progress_bar.place(x=358, y=320)
    progress_percent = tk.StringVar()
    progress_percent_label = tk.Label(main_frame, textvariable=progress_percent, bg='#87CEEB')
    progress_percent_label.place(x=565, y=319)
    elapsed_time_label = tk.Label(main_frame, text="耗时：0分0秒", bg='#87CEEB')
    elapsed_time_label.place(x=270, y=320)
    start_time = time()
    simulate_work_button = tk.Button(main_frame, text="更新系统", command=start_client_thread)
    simulate_work_button.place(x=610, y=317)

    def get_cpu_kel():
        """查询设备cpu核心数"""
        output = execute_command(f"{cmd_adb} shell cat /proc/cpuinfo")
        lines = output.split('\n')
        processors = [line.split(':')[1].strip() for line in lines if 'processor' in line]
        try:
            hxs = int(processors[-1]) + 1
            logger.info(f"设备为 {hxs} 核CPU")
            messagebox.showinfo("设备核心数", f"设备为 {hxs} 核CPU")
        except IndexError as e:
            logger.info(e)
            messagebox.showwarning("设备核心数", "请检查设备是否正确连接")

    # get_cpu_kel_button = tk.Button(main_frame, text="CPU核数", command=get_cpu_kel)
    # get_cpu_kel_button.place(x=610, y=357)

    def start_monitor():
        """开启服务监控，获取实时应用状态"""
        cmd = f"{cmd_adb} shell am monitor"
        process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                                   creationflags=subprocess.CREATE_NO_WINDOW)
        logger.info(process)
        t = Thread(target=read_output, args=(process,))
        t.start()

    def read_output(process):
        """读取返回数据并在文本框展示"""
        while 1:
            line = process.stdout.readline()
            logger.info(f"监控服务：{line}")
            if not line:
                break
            if text_widget.winfo_exists():
                text_widget.insert(tk.END, line)
                text_widget.see(tk.END)

    text_widget = tk.Text(main_frame, width=47, height=7)
    text_widget.place(x=270, y=355)
    packages_monitor_button = tk.Button(main_frame, text="服务监控", command=start_monitor)
    packages_monitor_button.place(x=610, y=400)

    def growingio_adb_forward():
        """设置端口转发"""
        try:
            execute_command(f"{cmd_adb} forward tcp:9001 tcp:9001")
            print("端口转发设置完成")
            return True
        except Exception as e:
            print(f"设置端口转发失败：{e}")
            return False

    def growingio_receive_data():
        growingio_adb_forward()
        # 创建一个socket对象
        client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # 增加接收缓冲区大小
        client.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 5 * 1024 * 1024)
        # 设置超时时间
        client.settimeout(30)
        # 连接到服务器
        client.connect(('127.0.0.1', 9001))
        logger.info('已连接到埋点数据服务器')
        # 发送日志导出请求
        message = 'logExport'
        client.sendall(message.encode('utf-8'))
        try:
            while True:
                # 分块接收数据
                data = client.recv(8192)  # 每次接收最多8192字节
                if not data:
                    logger.warning('连接已被服务器关闭。')
                    break
                print('接收到数据:', data)
                # 首先，找到 '[' 的位置
                bracket_index = data.find(b'[')
                # 如果找到了 '['，提取子串
                if bracket_index != -1:
                    extracted_data = data[bracket_index:]
                    # 解码字节串为UTF-8编码的字符串
                    data_string = extracted_data.decode('utf-8')
                    json_list = json.loads(data_string)
                    with open(f'{paths()}growingio_data.txt', 'w', encoding='utf-8') as file:
                        file.write(str(json_list).replace("'", ''))
                    messagebox.showinfo("埋点数据导出结果", "数据已保存到 growingio_data.txt 文件")
                else:
                    logger.warning("在数据中找不到“[”。")
                    extracted_data = b''
                    data_string = extracted_data.decode('utf-8')
                    with open(f'{paths()}growingio_data.txt', 'w', encoding='utf-8') as file:
                        file.write(data_string)
                    messagebox.showinfo("埋点数据导出结果", "数据已保存到 growingio_data.txt 文件")
                logger.info("数据已保存到 growingio_data.txt 文件")
                client.sendall(b'logClose')
                logger.info('连接已关闭')
        except socket.timeout:
            logger.warning('socket超时。未收到任何数据。')
        finally:
            # 关闭连接
            client.close()

    def on_combobox_change(*args):
        selection = combobox1.get()
        if selection == "CPU核数":
            # 执行针对选项1的操作
            print(f"Combobox选择了：{selection}")
            get_cpu_kel()
        elif selection == "埋点数据":
            # 执行针对选项2的操作
            print(f"Combobox选择了：{selection}")
            growingio_receive_data()

    combobox1 = ttk.Combobox(main_frame, values=["CPU核数", "埋点数据"], width=7)
    combobox1.place(x=607, y=357)
    combobox1.bind("<<ComboboxSelected>>", on_combobox_change)


def show_auxiliary():
    """辅助功能"""
    reset_frame()

    sjsj_char_sets = {
        '数字': string.digits,
        '小写字母': string.ascii_lowercase,
        '大写字母': string.ascii_uppercase,
        '特殊字符': string.punctuation
    }

    def generate_command(length=8, numbers=0, small_letters=0, large_letters=0, special_chars=0):
        """确定可用字符集合"""
        all_chars = ''
        if numbers:
            all_chars += sjsj_char_sets['数字']
        if small_letters:
            all_chars += sjsj_char_sets['小写字母']
        if large_letters:
            all_chars += sjsj_char_sets['大写字母']
        if special_chars:
            all_chars += sjsj_char_sets['特殊字符']
        if not all_chars or length <= 0:
            logger.error("至少要选择一种字符类别来生成密码")
            raise ValueError("至少要选择一种字符类别来生成密码")
        if 0 < length < 10:
            password = "".join(random.sample(all_chars, length))
            return password
        elif length >= 10:
            password = ''.join(random.choice(all_chars) for _ in range(length))
            return password

    def shield_button():
        """执行按钮动作"""
        lengths = app_name_entry.get().strip()
        logger.info(f"生成密码位数：{lengths}")
        selection = [check_var.get() for check_var in check_vars]
        selected_keys = [key for key, checked in zip(sjsj_char_sets.keys(), selection) if checked]
        logger.info(f"组合方式：{selected_keys}")
        if not bool(lengths) or not bool(selected_keys):
            messagebox.showwarning("随机密码", "请正确输入需要生成的密码位数并选择组合方式！")
        else:
            try:
                sjmm = generate_command(length=int(lengths), numbers=selection[0], small_letters=selection[1],
                                        large_letters=selection[2], special_chars=selection[3])
                logger.info(f"随机生成的密码是：{sjmm}")
                mmtext.delete(1.0, tk.END)
                mmtext.insert(tk.END, sjmm)
            except ValueError as e:
                logger.error(e)
                messagebox.showwarning("随机密码", "输入错误，请输入大于0的整数！")

    style = ttk.Style()
    style.configure("TLabelframe", background='#87CEEB')
    labelframe = ttk.Labelframe(main_frame, text="随机密码生成功能", style="TLabelframe")
    labelframe.place(x=0, y=0, width=210, height=155)
    app_name_label = tk.Label(labelframe, text="密码位数:")
    app_name_label.place(x=10, y=18)
    app_name_label.config(bg='#87CEEB')
    app_name_entry = tk.Entry(labelframe, width=5)
    app_name_entry.place(x=70, y=18)
    check_vars = []
    for i, key in enumerate(sjsj_char_sets.keys()):
        check_var = tk.IntVar()
        check_vars.append(check_var)
        chk = tk.Checkbutton(labelframe, text=key, variable=check_var)
        chk.place(x=10, y=45 + i * 20)
        chk.config(bg='#87CEEB')

    shield_button_an = tk.Button(labelframe, text="生成密码", command=shield_button)
    shield_button_an.place(x=130, y=11 + len(sjsj_char_sets) * 1)
    mmtext = tk.Text(labelframe, width=14, height=3)
    mmtext.place(x=90, y=82)

    def entry_time_s1(s1):
        """秒时间戳转本地时间"""
        try:
            time_str_s2 = ti.strftime("%Y-%m-%d %H:%M:%S", ti.localtime(int(s1)))
            logger.info(f"{s1}转换结果为：{time_str_s2}")
            return str(time_str_s2)
        except (OSError, ValueError):
            logger.error("输入的时间格式错误，请纠正后重新转换！")
            messagebox.showerror(title="时间戳转换", message="输入的时间格式错误，请纠正后重新转换！")

    def entry_time_ms1(ms1):
        """毫秒时间戳转本地时间"""
        try:
            ms = float(ms1) / 1000
            time_str_ms2 = datetime.datetime.fromtimestamp(ms).strftime("%Y-%m-%d %H:%M:%S")
            logger.info(f"{ms1}转换结果为：{time_str_ms2}")
            return str(time_str_ms2)
        except ValueError:
            logger.error("输入的时间格式错误，请纠正后重新转换！")
            messagebox.showerror(title="时间戳转换", message="输入的时间格式错误，请纠正后重新转换！")

    def entry_time_us1(us1):
        """微秒时间戳转换本地时间"""
        utc_dt = datetime.datetime(1970, 1, 1) + datetime.timedelta(microseconds=int(us1))
        beijing_dt = utc_dt + datetime.timedelta(hours=8)
        beijing_out_us = beijing_dt.strftime('%Y-%m-%d %H:%M:%S.%f')
        logger.info(f"当前微秒级时间戳：{beijing_out_us}")
        return str(beijing_out_us)[:-7]

    def time_stamp_s(s1):
        """本地时间转换为s时间戳"""
        try:
            timeStamp2 = int(ti.mktime(ti.strptime(s1, "%Y-%m-%d %H:%M:%S")))
            logger.info(f"{s1}当前秒级转换为：{timeStamp2}")
            return timeStamp2
        except ValueError:
            logger.error("输入的时间格式错误，请纠正后重新转换！")
            messagebox.showerror(title="北京时间转时间戳", message="输入的时间格式错误，请纠正后重新转换！")

    def time_stamp_ms(ms1):
        """本地时间转换为ms时间戳"""
        try:
            timeStamp2 = datetime.datetime.strptime(ms1, '%Y-%m-%d %H:%M:%S').timestamp()
            print(timeStamp2)
            timestamp_ms = int(timeStamp2) * 1000
            logger.info(f"{ms1}当前秒级转换为：{timestamp_ms}")
            return timestamp_ms
        except ValueError:
            logger.error("输入的时间格式错误，请纠正后重新转换！")
            messagebox.showerror(title="北京时间转时间戳", message="输入的时间格式错误，请纠正后重新转换！")

    def time_stamp_us(us1):
        """本地时间转换为us时间戳"""
        try:
            current_time = datetime.datetime.strptime(us1, '%Y-%m-%d %H:%M:%S')
            timestamp_s = int(current_time.timestamp())
            timestamp_us = timestamp_s * 1000000 + current_time.microsecond
            logger.info(f"{us1}当前秒级转换为：{timestamp_us}")
            return timestamp_us
        except ValueError:
            logger.error("输入的时间格式错误，请纠正后重新转换！")
            messagebox.showerror(title="北京时间转时间戳", message="输入的时间格式错误，请纠正后重新转换！")

    def entry_utc1():
        """utc国际时间转换为本地时间"""
        utc1 = entry_time_3.get().strip()
        try:
            try:
                # utc1 = "2022-06-15T09:15:41.52Z"
                utcTime2 = datetime.datetime.strptime(utc1, "%Y-%m-%dT%H:%M:%S.%fZ") + datetime.timedelta(hours=8)
                text3.delete(1.0, tk.END)
                text3.insert(tk.END, str(utcTime2))
            except ValueError:
                # 给定的UTC时间字符串
                # utc1 = "2023-04-13T15:30:00Z"
                utc_dt = datetime.datetime.fromisoformat(utc1.replace("Z", "+00:00"))
                beijing_tz_offset = datetime.timedelta(hours=8)
                beijing_dt = utc_dt + beijing_tz_offset
                beijing_time_str = beijing_dt.strftime("%Y-%m-%d %H:%M:%S")
                text3.delete(1.0, tk.END)
                text3.insert(tk.END, str(beijing_time_str))

        except ValueError:
            logger.error(f"{utc1}输入的时间格式错误，请纠正后重新转换！")
            messagebox.showerror(title='UTC时间转换', message="输入的时间格式错误，请纠正后重新转换！")

    def current_timestamp():
        """获取秒为单位的本地时间戳"""
        inttimes = int(ti.time())
        return inttimes

    def current_timestamp_ms():
        """获取毫秒为单位的本地时间戳"""
        inttimems = int(ti.time()) * 1000
        return inttimems

    def current_timestamp_us():
        """获取微秒为单位的本地时间戳"""
        current_time = datetime.datetime.now()
        timestamp_us = (current_time.timestamp() * 1000000) + current_time.microsecond
        return int(timestamp_us)

    def local_time():
        """获取本地时间戳"""
        get_time = time_combo3.get()
        if get_time:
            if get_time == "当前时间戳(s)":
                time_s = current_timestamp()
                text5.delete(1.0, tk.END)
                text5.insert(tk.END, str(time_s))
                logger.info(f"当前时间戳(s)转换结果为：{time_s}")
            elif get_time == "当前时间戳(ms)":
                time_ms = current_timestamp_ms()
                text5.delete(1.0, tk.END)
                text5.insert(tk.END, str(time_ms))
                logger.info(f"当前时间戳(ms)转换结果为：{time_ms}")
            else:
                time_us = current_timestamp_us()
                text5.delete(1.0, tk.END)
                text5.insert(tk.END, str(time_us))
                logger.info(f"当前时间戳(us)转换结果为：{time_us}")
        else:
            logger.warning("未选择获取条件")
            messagebox.showwarning(title="本地时间戳", message="请先选择时间条件")

    def gettime():
        """获取时间的函数"""
        dstr.set(ti.strftime("%H:%M:%S"))
        main_frame.after(1000, gettime)

    dstr = tk.StringVar()
    tk.Label(main_frame, textvariable=dstr, foreground="green", font=("Arial", 16), bg='#87CEEB').place(x=220, y=10)
    gettime()

    def timestamp_to_time():
        """时间戳转北京时间"""
        get_time = time_combo1.get()
        srz = entry_time_1.get().strip()
        if get_time:
            if get_time == "秒(s)":
                sjc_s = entry_time_s1(srz)
                text1.delete(1.0, tk.END)
                text1.insert(tk.END, sjc_s)
            elif get_time == "毫秒(ms)":
                sjc_ms = entry_time_ms1(srz)
                text1.delete(1.0, tk.END)
                text1.insert(tk.END, sjc_ms)
            else:
                sjc_us = entry_time_us1(srz)
                text1.delete(1.0, tk.END)
                text1.insert(tk.END, sjc_us)
        else:
            logger.warning("未选择获取条件")
            messagebox.showwarning(title="时间戳转北京时间", message="请先选择时间条件")

    def time_to_timestamp():
        """北京时间转时间戳"""
        get_timestamp = time_combo2.get()
        srz = entry_time_2.get().strip()
        if get_timestamp:
            if get_timestamp == "秒(s)":
                bjsj_s = time_stamp_s(srz)
                text2.delete(1.0, tk.END)
                text2.insert(tk.END, str(bjsj_s))
            elif get_timestamp == "毫秒(ms)":
                bjsj_ms = time_stamp_ms(srz)
                text2.delete(1.0, tk.END)
                text2.insert(tk.END, str(bjsj_ms))
            else:
                bjsj_us = time_stamp_us(srz)
                text2.delete(1.0, tk.END)
                text2.insert(tk.END, str(bjsj_us))
        else:
            logger.warning("未选择获取条件")
            messagebox.showwarning(title="北京时间转时间戳", message="请先选择时间条件")

    time_combo3 = ttk.Combobox(main_frame, values=["当前时间戳(s)", "当前时间戳(ms)", "当前时间戳(us)"],
                               state="readonly", width=12)
    time_combo3.place(x=315, y=13)
    time_button2 = tk.Button(main_frame, text="当前时间戳>", command=local_time)
    time_button2.place(x=435, y=10)
    text5 = tk.Text(main_frame, width=18, height=2)
    text5.place(x=534, y=10)
    time_label1 = tk.Label(main_frame, text="时间戳:")
    time_label1.place(x=215, y=53)
    time_label1.config(bg='#87CEEB')
    entry_time_1 = tk.Entry(main_frame, width=18)
    entry_time_1.place(x=260, y=53)
    time_combo1 = ttk.Combobox(main_frame, values=["秒(s)", "毫秒(ms)", "微秒(us)"], state="readonly", width=7)
    time_combo1.place(x=403, y=53)
    time_button1 = tk.Button(main_frame, text="转换", command=timestamp_to_time)
    time_button1.place(x=482, y=50)
    text1 = tk.Text(main_frame, width=18, height=2)
    text1.place(x=534, y=50)
    time_label2 = tk.Label(main_frame, text="时间:")
    time_label2.place(x=215, y=88)
    time_label2.config(bg='#87CEEB')
    entry_time_2 = tk.Entry(main_frame, width=18)
    entry_time_2.place(x=260, y=88)
    time_combo2 = ttk.Combobox(main_frame, values=["秒(s)", "毫秒(ms)", "微秒(us)"], state="readonly", width=7)
    time_combo2.place(x=403, y=88)
    time_button2 = tk.Button(main_frame, text="转换", command=time_to_timestamp)
    time_button2.place(x=482, y=85)
    text2 = tk.Text(main_frame, width=18, height=2)
    text2.place(x=534, y=85)
    time_label3 = tk.Label(main_frame, text="UTC时间:")
    time_label3.place(x=215, y=124)
    time_label3.config(bg='#87CEEB')
    entry_time_3 = tk.Entry(main_frame, width=22)
    entry_time_3.place(x=275, y=124)
    time_button3 = tk.Button(main_frame, text="转换>", command=entry_utc1)
    time_button3.place(x=447, y=121)
    text3 = tk.Text(main_frame, width=22, height=2)
    text3.place(x=506, y=121)

    def adb_inputs():
        """输入内容"""
        texts = adb_input.get().strip()
        logger.info(f"输入内容：{texts}")
        a = execute_command(f"{cmd_adb} shell input text {texts}")
        if "Exception occurred while executing 'text'" in a:
            logger.error(a)
            messagebox.showerror(title="输入内容", message="暂不支持中文输入，中文请用空间输入法输入")

    def adb_enter():
        """执行回车按钮"""
        execute_command(f"{cmd_adb} shell input keyevent 66")
        logger.info("执行enter回车成功")

    adb_input_label = tk.Label(main_frame, text="请键盘输入：")
    adb_input_label.place(x=5, y=165)
    adb_input_label.config(bg='#87CEEB')
    adb_input = tk.Entry(main_frame)
    adb_input.place(x=80, y=165)
    adb_input_button = tk.Button(main_frame, text="确定", command=adb_inputs)
    adb_input_button.place(x=238, y=160)
    adb_enter_button = tk.Button(main_frame, text="回车", command=adb_enter)
    adb_enter_button.place(x=290, y=160)

    def adb_shell_cmd():
        """adb shell命令"""
        adb_ml = adb_shell_entry.get().strip()
        cmd_shell = f"{cmd_adb} {adb_ml}"
        logger.info(f"执行命令：{cmd_shell}")
        adb_shell_output = execute_command(cmd_shell)
        logger.info(f"查询结果：{adb_shell_output}")
        if "命令执行出错" in adb_shell_output:
            adb_shell_text.delete(1.0, tk.END)
            adb_shell_text.insert(1.0, f"请输入adb以后的shell命令,如：devices，或 shell ps等，不需要输入 adb devices。")
        else:
            adb_shell_text.delete(1.0, tk.END)
            adb_shell_text.insert(1.0, adb_shell_output)

    adb_shell_label = tk.Label(main_frame, text="输入查询命令：")
    adb_shell_label.place(x=345, y=165)
    adb_shell_label.config(bg='#87CEEB')
    adb_shell_entry = tk.Entry(main_frame, width=25)
    adb_shell_entry.place(x=430, y=165)
    adb_shell_button = tk.Button(main_frame, text="查询",
                                 command=lambda: threading.Thread(target=adb_shell_cmd).start())
    adb_shell_button.place(x=625, y=160)
    adb_shell_text = tk.Text(main_frame, width=91, height=18)
    adb_shell_text.place(x=20, y=205)


def show_compare_files():
    """实时文件比较功能"""
    reset_frame()

    def compare_jsons():
        """比较json文件"""
        json_str1 = json_entry1.get("1.0", tk.END).strip()
        json_str2 = json_entry2.get("1.0", tk.END).strip()
        try:
            data1 = json.loads(json_str1)
            data2 = json.loads(json_str2)
            json_str1 = json.dumps(data1, indent=4, sort_keys=True)
            json_str2 = json.dumps(data2, indent=4, sort_keys=True)
            diff = difflib.unified_diff(json_str1.splitlines(), json_str2.splitlines(), fromfile='JSON 1',
                                        tofile='JSON 2')
            decoded_diff = []

            for line in diff:
                # 解码可能存在的Unicode转义序列，使其在文本框中正确显示
                decoded_line = line.encode('latin1').decode('unicode_escape')
                decoded_diff.append(decoded_line)
            if not decoded_diff:
                output_text.delete(1.0, tk.END)
                output_text.insert(tk.END, "两个JSON文件内容完全相同。")
                return
            output_text.delete(1.0, tk.END)
            for line in decoded_diff:
                output_text.insert(tk.END, line + '\n')

        except json.JSONDecodeError:
            output_text.delete(1.0, tk.END)
            output_text.insert(tk.END, "输入的不是有效的JSON格式，请检查后重新输入。")
        except Exception as e:
            output_text.delete(1.0, tk.END)
            output_text.insert(tk.END, f"发生错误：{str(e)}")

    # JSON数据输入框
    json_label1 = tk.Label(main_frame, text="第一个JSON数据:")
    json_label1.place(x=120, y=5)
    json_entry1 = tk.Text(main_frame, height=13, width=45)
    json_entry1.place(x=10, y=30)

    json_label2 = tk.Label(main_frame, text="第二个JSON数据:")
    json_label2.place(x=450, y=5)
    json_entry2 = tk.Text(main_frame, height=13, width=45)
    json_entry2.place(x=345, y=30)

    # 比较按钮
    compare_button = tk.Button(main_frame, text="对比json数据", command=compare_jsons)
    compare_button.place(x=295, y=220)

    # 输出结果文本框
    output_text = tk.Text(main_frame, height=14, width=93)
    output_text.place(x=10, y=258)


def show_wifi():
    """wifi查看器功能"""
    reset_frame()

    def get_stored_wifi_networks():
        """
        获取所有存储的WiFi网络配置文件
        """
        command = "netsh wlan show profiles"
        try:
            output = subprocess.check_output(command, shell=True, text=True)
            logger.info(f"查询结果：{output}")
            # profiles = [line.split(": ")[1] for line in output.split("\n") if "所有用户配置文件 : " in line]
            # print(profiles)
            profiles = re.findall(r"所有用户配置文件 : (.+)", output, re.MULTILINE)
            return profiles
        except:
            print("数据为空")
            return None

    def get_wifi_network_details(wifi_name):
        """
        获取指定SSID的WiFi网络的详细信息
        """
        command = f"netsh wlan show profiles name={wifi_name} key=clear"
        try:
            output = subprocess.check_output(command, shell=True, text=True)
            # 解析输出以获取密码
            password_search = re.search(r"关键内容\s*:\s*(\S+)", output)
            wifi_pwd = password_search.group(1) if password_search else None
            if wifi_pwd is None:
                texts = subprocess.check_output(f'netsh wlan show profiles name="{wifi_name}" key=clear', shell=True,
                                                text=True)
                colon_position = texts.find('关键内容            :')
                if colon_position != -1:
                    key_content = texts[colon_position + len('关键内容            :'):].strip().splitlines()
                    return key_content[0]
                else:
                    return "未查询到密码"
            return wifi_pwd
        except subprocess.CalledProcessError as e:
            print(f"Error: {e}")
            return None

    def wifi_run():
        """执行程序"""
        ssid_pwd = []
        stored_networks = get_stored_wifi_networks()
        if stored_networks:
            for ssid in stored_networks:
                password = get_wifi_network_details(ssid)
                # print(f"SSID: {ssid}, 密码: {password}")
                ssid_pwd.append((ssid, password))
            return ssid_pwd
        else:
            logger.warning("No wifi")
            return " "

    # 创建Treeview控件
    tree = ttk.Treeview(main_frame, columns=("WiFi名称", "WiFi密码"), show="headings")
    tree.column("WiFi名称", width=150)
    tree.column("WiFi密码", width=150)
    tree.heading("WiFi名称", text="WiFi名称")
    tree.heading("WiFi密码", text="WiFi密码")
    data = wifi_run()
    # 将数据填入表格
    for item in data:
        tree.insert("", "end", values=item)
    # 将Treeview控件添加到主窗口
    tree.pack(fill=BOTH, expand=YES)
    # tree.place(x=10, y=10)


def show_help():
    """帮助菜单"""
    reset_frame()
    help_text = """
    V2.0.8版本说明：
    1、修改部分模糊的名词。
    2、修复wifi信息为空时的显示bug。\n
    工具使用说明：
    1、基本功能
        对应一些常用的基础功能
    2、其他功能
        主要用于眼镜投屏和录屏已经wifi相关功能
    3、系统功能
        涉及到系统交互的属性和功能，包括高通系统刷机辅助和相关系统功能
    4、随机密码
        主要用于生成一些随机密码，密码强度可自由组合
    5、主题
        用于当前工具的皮肤展示，可根据喜好自定义选择，默认使用第一种主题皮肤
    """
    help_label = tk.Label(main_frame, text="关于", font=('Arial', 10), justify="left", bg='#87CEEB')
    help_label.place(x=5, y=10)
    help_label.config(text=help_text, fg="green")


def reset_frame():
    """重置菜单框架"""
    for widget in main_frame.winfo_children():
        widget.destroy()


if __name__ == '__main__':
    root = tk.Tk()
    root.title('移动终端工具')
    root.wm_iconbitmap(f"{paths('bin')}gj.ico")
    root.geometry('680x480')
    root.resizable(False, False)

    menu_bar = tk.Menu(root)

    function_menu = tk.Menu(menu_bar, tearoff=0)
    function_menu.add_command(label="基本功能", command=show_basic)
    function_menu.add_separator()
    function_menu.add_command(label="网络投屏", command=show_common)
    function_menu.add_separator()
    function_menu.add_command(label="系统功能", command=show_system)

    auxiliary_menu = tk.Menu(menu_bar, tearoff=0)
    auxiliary_menu.add_command(label="日常工具", command=show_auxiliary)
    auxiliary_menu.add_separator()
    auxiliary_menu.add_command(label='数据比对', command=show_compare_files)
    auxiliary_menu.add_separator()
    auxiliary_menu.add_command(label="WiFi查看器", command=show_wifi)

    help_menu = tk.Menu(menu_bar, tearoff=0)
    help_menu.add_command(label="关于", command=show_help)
    help_menu.add_separator()
    help_menu.add_command(label="退出", command=root.quit)

    menu_bar.add_cascade(label="更多功能", menu=function_menu)
    menu_bar.add_cascade(label="辅助功能", menu=auxiliary_menu)
    menu_bar.add_cascade(label="帮助", menu=help_menu)

    main_frame = tk.Frame(root)
    main_frame.place(x=0, y=0, relwidth=1, relheight=1)

    main_frame.config(bg='#87CEEB')

    initialize()
    show_basic()

    root.config(menu=menu_bar)
    root.mainloop()
